<template>
  <div>
    <div>
      <el-row>
        <el-col :span="12">
          <el-page-header @back="goBack" content="新增商品"></el-page-header>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-button class="ml-5" type="danger" @click="clearProduct">清空</el-button>
          <el-button class="ml-5" type="primary" @click="insertProduct">新增</el-button>
        </el-col>
      </el-row>
      <div>
        <el-row :gutter="20">
          <el-form :rules="rules" ref="form" :model="product" label-width="120px">
            <!--                        封面-->
            <el-form-item label="封面图">
              <el-upload
                  class="avatar-uploader"
                  :action="`${$ysyApi}/api/UpLoadFile/`"
                  :headers="headers"
                  name="file"
                  :show-file-list="false"
                  :on-success="uploadProductCover"
                  :before-upload="beforeAvatarUpload">
                <img v-if="ShowImageUrl" :src="ShowImageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
            <!--                        轮播-->
            <el-form-item label="轮播图">
              <el-upload
                  class="avatar-uploader"
                  list-type="picture-card"
                  :action="`${$ysyApi}/api/UpLoadFile/`"
                  :headers="headers"
                  name="file"
                  :on-success="uploadProductBanner"
                  :on-remove="handleRemove"
                  :before-upload="beforeAvatarUpload">
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <!--                        商品条码-->
            <el-form-item label="商品条码" prop="productBar">
              <el-input
                  placeholder="请输入商品条码"
                  v-model="product.productBar"
                  clearable>
              </el-input>
            </el-form-item>
            <!--                        商品名称-->
            <el-form-item label="商品名称">
              <el-input
                  placeholder="请输入商品名称"
                  v-model="product.productName"
                  clearable>
              </el-input>
            </el-form-item>
            <!--                        商品类型-->
            <el-form-item label="商品类型">
              <el-select v-model="product.productType" placeholder="请选择您的商品类型">
                <el-option v-for="item in productCategory" :key="item.productCategoryId"
                           :label="item.productCategoryName" :value="item.productCategoryId"></el-option>
              </el-select>
            </el-form-item>
            <!--                        商品价格-->
            <el-form-item label="商品价格">
              <el-input
                  placeholder="请输入商品价格"
                  v-model="product.prodcutPrice"
                  clearable>
              </el-input>
            </el-form-item>
            <!--                        库存-->
            <el-form-item label="商品库存">
              <el-input
                  type="number"
                  placeholder="请输入商品库存"
                  v-model="product.repertory"
                  clearable>
              </el-input>
            </el-form-item>
            <!--                        商品位置-->
            <el-form-item label="商品位置">
              <el-select v-model="product.productPlaceAddress" placeholder="请选择您的商品状态">
                <el-option v-for="item in productConfigAddress" :label="item.sysConfigName"
                           :value="item.sysConfigId"></el-option>
              </el-select>
            </el-form-item>
            <!--                        商品层数-->
            <el-form-item label="商品层数">
              <el-input
                  type="number"
                  placeholder="请输入商品位于层数"
                  v-model="product.productPlies"
                  clearable>
              </el-input>
            </el-form-item>
            <!--                        推荐指数-->
            <el-form-item label="推荐指数">
              <el-input
                  type="number"
                  placeholder="请输入商品推荐指数"
                  v-model="product.recommendationIndex"
                  clearable>
              </el-input>
            </el-form-item>
            <!--                        热门指数-->
            <el-form-item label="热门指数">
              <el-input
                  type="number"
                  placeholder="请输入商品热门指数"
                  v-model="product.hotIndex"
                  clearable>
              </el-input>
            </el-form-item>
            <!--                        简介-->
            <el-form-item label="商品简介">
              <el-input
                  type="textarea"
                  maxlength="255"
                  :autosize="{ minRows: 6, maxRows: 6}"
                  placeholder="请输入商品简介"
                  show-word-limit
                  v-model="product.productIntro"
                  clearable>
              </el-input>
            </el-form-item>
            <!--                        商品状态-->
            <el-form-item label="商品状态">
              <el-select v-model="product.productStatus" placeholder="请选择您的商品状态">
                <el-option label="在售" value="0"></el-option>
                <el-option label="售罄" value="1"></el-option>
                <el-option label="下架" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-row>
      </div>
    </div>

  </div>
</template>

<script>
export default {
  name: "InsertProduct",
  data() {
    return {
      loginStatus: true,
      dialogImageUrl: '',
      dialogVisible: false,
      ShowImageUrl: '',
      //图片上传请求头
      headers: {
        Authorization: ''
      },
      productBanner: [],
      productConfigAddress: '',
      productCategory: '',
      product: {
        productBar: '',
        productName: '',
        productType: '',
        prodcutPrice: '',
        repertory: '0',
        productPlaceAddress: '',
        productPlies: '1',
        recommendationIndex: '1',
        hotIndex: '1',
        productIntro: '',
        productStatus: '',
        productCover: '',//封面
        productBanner: "",//修改用的轮播图
      },
      rules: {
        productBar: [{required: true, message: '请输入商品条形码'}],
        productName: [{required: true, message: '请输入商品名称'}],
        productType: [{required: true, message: '请选择商品类型'}],
        prodcutPrice: [{required: true, message: '请输入商品价格'}],
        repertory: [{required: true, message: '请输入商品库存'}],
        productPlaceAddress: [{required: true, message: '请选择商品货架位置'}],
        productPlies: [{required: true, message: '请选择商品货架层数'}],
        recommendationIndex: [{required: true, message: '请输入商品推荐度'}],
        hotIndex: [{required: true, message: '请输入商品热度'}],
        productIntro: [{required: true, message: '请输入商品简介'}],
        productStatus: [{required: true, message: '请选择商品状态'}],
      },
    }
  },
  created() {
    this.findSysConfig()
    this.findProductCategory()
    this.headers.Authorization = JSON.parse(localStorage.getItem('user')).token
  },
  methods: {
    goBack() {
      this.$router.back()
    },
    //上传封面图片
    uploadProductCover(response, file, fileList) {
      this.ShowImageUrl = this.$ysyApi + response.message
      this.product.productCover = response.message
    },
    //修改banner图片
    uploadProductBanner(response, file, fileList) {
      this.productBanner.push(response.message)
    },
    //删除banner图片
    handleRemove(file, fileList) {
      for (let i = 0; i < this.productBanner.length; i++) {
        if (this.productBanner[i] == file.response.message) {
          this.productBanner.splice(i, 1)
        }
      }
    },
    //判断上传文件是否为jpeg/png图片
    beforeAvatarUpload(file) {
      let isJPG = false;
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg') {
        isJPG = true;
      }
      if (!isJPG) {
        this.$message.error('上传只能是图片格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //关闭警告提示框
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {
          });
    },
    //获取所有货架位置
    findSysConfig() {
      this.$axios({
        url: this.$api.FindSysConfig,
        method: 'get',
        params: {
          sysConfigName: '商品货架位置'
        }
      }).then(res => {

          this.productConfigAddress = res.data

      })
    },
    //获取所有商品类型
    findProductCategory() {
      this.$axios({
        url: this.$api.FindProductCategory,
        method: 'get',
      }).then(res => {

          this.productCategory = res.data

      })
    },
    //新增商品信息
    insertProduct() {
      if (this.product.productCover == '') {
        alert("请选择商品封面图片！")
        return
      }
      this.product.productBanner = ''
      for (let i = 0; i < this.productBanner.length; i++) {
        if (i == 0) {
          this.product.productBanner = "["
        }
        this.product.productBanner += "\"" + this.productBanner[i] + "\""
        if (i != this.productBanner.length - 1) {
          this.product.productBanner += ","
        }
        if (i == this.productBanner.length - 1) {
          this.product.productBanner += "]"
        }
      }
      if (this.product.productBanner == '') {
        alert("请选择商品轮播图！")
        return
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          //通过验证
          this.$axios({
            url: this.$api.InsertProduct,
            method: 'post',
            headers: {'content-type': 'multipart/form-data'},
            data: this.product
          }).then(res => {
            this.$notify({
              title: '成功',
              message: '商品添加成功',
              type: 'success'
            });
            this.$router.back()
          })
        } else {
          //未通过验证
          alert('请填写完整')
          return false;
        }
      });
    },
    //清空商品信息
    clearProduct() {
      this.product = {
        productBar: '',
        productName: '',
        productType: '',
        productCategoryName: '',
        prodcutPrice: '',
        repertory: '0',
        sysConfigName: '',
        sysConfigContent: '',
        recommendationIndex: '1',
        hotIndex: '1',
        productIntro: '',
        productStatus: '',
        productCover: '',//封面
        productBanner: "",//修改用的轮播图
      }
    },

  }
}
</script>

<style>
.mlr10 {
  margin: 10px 0px;
}

.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n+1) {
  background-color: #d3dce6;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>